package utils

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

// 没有ratelimit的请求
func HandleUserInfoRequest(url, value string) (string, error) {
	// 简单的url拼接
	if value != "" {
		url = fmt.Sprintf("%s?value=%s", url, value)
	}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Panic("err1: ", err)
	}
	// 使用 "http_retryable"
	httpClient := GetHttpClient(GetUserInfoRateLimiter, nil)
	res, err := httpClient.Do(req)

	if err != nil {
		fmt.Println("error>> ", err)
		return "", err
	}

	defer res.Body.Close()
	body, err1 := ioutil.ReadAll(res.Body)
	if err1 != nil {
		return "", err1
	}
	return string(body), nil
}

// 带ratelimit的请求
func HandleUserInfoRateLimitRequest(url, value string) (string, error) {
	// 先进行ratelimit的校验
	// !ok 表示触发了限流，不继续进行请求~而是等一下！
	for ok, _ := CheckRateLimit(GetUserInfoRateLimiter); !ok; ok, _ = CheckRateLimit(GetUserInfoRateLimiter) {
		// TODO 这里可以根据实际调整，这里为了演示效果设置的长点
		randSec := 3.1
		fmt.Println("需要等待: ", randSec)
		time.Sleep(time.Second * time.Duration(randSec))
	}

	// 简单的url拼接
	if value != "" {
		url = fmt.Sprintf("%s?value=%s", url, value)
	}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Panic("err1: ", err)
	}
	// 使用 "http_retryable"
	httpClient := GetHttpClient(GetUserInfoRateLimiter, nil)
	res, err := httpClient.Do(req)

	if err != nil {
		fmt.Println("error>> ", err)
		return "", err
	}

	defer res.Body.Close()
	body, err1 := ioutil.ReadAll(res.Body)
	if err1 != nil {
		return "", err1
	}
	return string(body), nil
}
